from django.db import models


class MyCharField(models.Field):
    # 自定义char类型的字段类
    def __init__(self, max_length, *args, **kwargs):
        self.max_length = max_length
        super().__init__(max_length=max_length, *args, **kwargs)

    def db_type(self, connection):
        # 限定生成的数据库表字段类型char 长度为max_length指定的值
        return 'char(%s)' % self.max_length


# Create your models here.
# class User(models.Model):
#     """用户表"""
#     # uid = models.AutoField(primary_key=True)  # uid int primary key auto_increment
#     name = models.CharField(max_length=32)  # name varchar(32)
#     pwd = models.IntegerField()  # pwd int

# info = models.TextField()

# models.CharField   varchar(max_length) 参数必带
# models.IntegerField int
# models.AutoField   主键自增字段 primary_key
# models.BooleanField  布尔值 传存0或1
# models.DateField      年月日   auto_now 每次自动更新当天时间  auto_now_add 第一次自动更新当天时间
# models.DateTimeField  年月日十分秒
# models.DecimalField   float max_digits  decimal_places
# models.EmailField     varchar
# models.TextField  文本类型 存没有限制的大段文本
# models.FileField  传文件对象 存地址路径
# def __str__(self):
#     return '用户对象：%s' % self.name


# class Userinfo(models.Model):
#     username = models.CharField(max_length=32)
#     password = models.IntegerField()


class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    publish_time = models.DateField(auto_now_add=True)

    # 添加两个普通字段
    ku_cun = models.IntegerField(default=1000)
    mai_chu = models.IntegerField(null=True)

    desc = MyCharField(max_length=32, null=True)

    publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)  # 一对多  外键字段在多的一方
    authors = models.ManyToManyField(to='Author')  # 多对多 外键字段建在查询频率较高的表中

    def __str__(self):
        return f'书籍对象:{self.title}'


class Publish(models.Model):
    title = models.CharField(max_length=32)
    email = models.EmailField()

    def __str__(self):
        return f'出版社对象:{self.title}'


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)  # 一对一 外键字段建在查询频率较高的表中

    def __str__(self):
        return f'作者对象{self.name}'


class AuthorDetail(models.Model):
    phone = models.BigIntegerField()
    addr = models.CharField(max_length=64)

    def __str__(self):
        return f'作者详情对象:{self.title}'

class BookUser(models.Model):
    username = models.CharField(max_length=32)
    gender_choice =(
        (1, '男性'),
        (2, '女性'),
        (3, '其他')
    )
    gender = models.IntegerField(choices=gender_choice)